﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MyAlbum.Model;
using MyAlbum.Services;
using MyAlbum.Utility;

namespace PersonalAlbum.Controllers
{
    public class CategoriesController : ApplicationController
    {
        private ISectionService _sectionService;
        public CategoriesController() : this(ObjectFactory.GetInstance<ISectionService>()) { }
        public CategoriesController(ISectionService sectionService)
        {
            this._sectionService = sectionService;
        }
        //[OutputCache(Duration = 120000, VaryByParam = "none", VaryByCustom = "lang")]
        public ActionResult Index(int page)
        {
            WebLogger.WriteToFile("section index");
            WebLogger.Trace("section index");
            ((PersonalAlbumModel)ViewData.Model).Sections=WebCacheManager.Instance.GetSections();
            try
            {
                return View(ViewData.Model);
            }
            catch (Exception e1)
            {
                return new TextResult(e1.Message);
            }
        }

        /// <summary>
        /// An ajax request
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult ShowCreate()
        {
            ViewData["returnUrl"] = Request.Params["returnUrl"];
            return PartialView("AddSection",ViewData.Model);
        }

        /// <summary>
        /// An ajax request
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult ShowUpdate(string id)
        {
            ((PersonalAlbumModel)ViewData.Model).CurrentSection= this._sectionService.GetItemById(id);
            ViewData["returnUrl"] = Request.Params["returnUrl"];
            return PartialView("EditSection", ViewData.Model);
        }



        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = RolesManager.AdminRoles)]
        //[ValidateAn tiForgeryToken()]
        public ActionResult Delete(string id)
        {
            WebLogger.Trace("delete section");

            try
            {
                var s = this._sectionService.GetItemById(id);
                if (s != null)
                {
                    Utils.DeleteImage(s.ContentUrl);
                    this._sectionService.DeleteItem(s);
                    WebLogger.Trace("section deleted");
                }
                else
                {
                    WebLogger.Warning("section " + id + " not found for delete");
                }
                return RedirectToAction("Index");
            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1, "error deleting section");
                ((PersonalAlbumModel)ViewData.Model).ErrorMessage = ((PersonalAlbumModel)ViewData.Model).Localize("Global.Error");
                ((PersonalAlbumModel)ViewData.Model).Sections = WebCacheManager.Instance.GetSections();
                return View("Index", ViewData.Model);
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        //[ValidateAn tiForgeryToken()]
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult Update(string id)
        {
            WebLogger.Trace("update section");


            try
            {
                bool delete = Request.Form["Section.Delete"] == null ?
                   false :
                   Request.Form["Section.Delete"].Equals("true",
                   StringComparison.InvariantCultureIgnoreCase);
                Section s = this._sectionService.GetItemById(id);
                if (s != null)
                {


                    if (delete)
                    {
                        Utils.DeleteImage(s.ContentUrl);
                        s.ContentUrl = null;
                    }
                    UpdateModel<Section>(s, "Section", new[] { "Description", "Name", "Visible" });
                    if (Request.Files["Section.Image"] != null &&
                        Request.Files["Section.Image"].ContentLength > 0)
                    {
                        if (!delete)
                        {
                            Utils.DeleteImage(s.ContentUrl);
                        }
                        s.ContentUrl = Utils.SaveFile(Request.Files["Section.Image"]);
                    }
                    this._sectionService.UpdateItem(s,new ModelStateWrapper(ModelState) );
                    WebCacheManager.Instance.RemoveItem("sections");
                    WebLogger.Trace("section updated");
                }
                else
                {
                    WebLogger.Warning("section " + id + " not found for update");
                }
                return RedirectToAction("Index");

            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1, "error updating section");
               ((PersonalAlbumModel)ViewData.Model).ErrorMessage  =((PersonalAlbumModel)ViewData.Model).Localize("Global.Error");
               ((PersonalAlbumModel)ViewData.Model).Sections = WebCacheManager.Instance.GetSections();
                return View("Index",ViewData.Model);
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        //[ValidateAn tiForgeryToken()]
        [Authorize(Roles = RolesManager.AddItemsRoles)]
        public ActionResult Create()
        {
            WebLogger.Trace("create section");

            try
            {

                Section s = new Section();
                UpdateModel<Section>(s, null, new[] { "Name", "Description", "Visible" }, new[] { "Id" });
                
                if (Request.Files["Image"] != null &&
                   Request.Files["Image"].ContentLength > 0)
                {
                    s.ContentUrl = Utils.SaveFile(Request.Files["Image"]);
                }
                this._sectionService.AddItem(s, new ModelStateWrapper(ModelState));
                WebCacheManager.Instance.RemoveItem("sections");
                WebLogger.Trace("section created");
                return RedirectToAction("Index");

            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1);
                ((PersonalAlbumModel)ViewData.Model).ErrorMessage = ((PersonalAlbumModel)ViewData.Model).Localize("Global.Error");
                ((PersonalAlbumModel)ViewData.Model).Sections = WebCacheManager.Instance.GetSections();
                return View("Index", ViewData.Model);

            }
        }
    }
}
